<!--
 * @Author: 黄达全
 * @Date: 2024-07-29 14:34:31
 * @LastEditTime: 2024-08-30 19:00:00
-->
<!--
 * @Author: 黄达全
 * @Date: 2024-07-29 14:34:31
 * @LastEditTime: 2024-08-21 18:28:47
-->
<script lang="ts" setup>
import leftTab from "./components/leftTab.vue"
import filterFormComponent from "./components/filterForm.vue"
import { ref, reactive, watch } from "vue"
import { useTable } from "@/hooks/useTable"
import GoodsApi, { GoodsItem, GoodsAddForm, GoodsFilterForm } from "@/api/model/goods"
import { FormRules } from "element-plus"
import drawer from "@/components/drawer.vue"
import selectImage from "@/components/selectImage.vue"
import { imageApi } from "@/api/model/image"
import { JwtTokenConstant } from "@/common/constant"
import tool from "@/utils/tool"
import { ElMessage } from "element-plus"
import useElementPlus from "@/hooks/useElementPlus"
const { message, messageBox } = useElementPlus()

const token = tool.data.get(JwtTokenConstant.token)

const goodsTab = ref("all")

// 过滤参数
const goodsFilterParams = reactive<GoodsFilterForm>({
    currentPage: 1,
    pageSize: 10
})
const isLuoJiDel=ref(true)

// 当标签页变化时，更新过滤参数
watch(goodsTab, (newVal) => {
    // 先重置过滤条件
   delete goodsFilterParams.status 
   delete goodsFilterParams.ischeck 
   delete goodsFilterParams.stockWarn 
   delete goodsFilterParams.isDelete 
    
    // 根据不同的标签设置不同的过滤条件
    switch(newVal) {
        case 'all': // 全部商品，不需要特殊过滤
        isLuoJiDel.value=true
        goodsFilterParams.isDelete = 0

            break
        case 'audit': // 审核中
        isLuoJiDel.value=true
        goodsFilterParams.isDelete = 0

            goodsFilterParams.ischeck = 0
            break
        case 'sale': // 出售中
        isLuoJiDel.value=true

            goodsFilterParams.status = 1 // 上架状态
            goodsFilterParams.ischeck = 1 // 审核通过
        goodsFilterParams.isDelete = 0

            break
        case 'off': // 已下架
        isLuoJiDel.value=true
        goodsFilterParams.isDelete = 0

            goodsFilterParams.status = 0 // 下架状态
            break
        case 'warning': // 库存预警
        isLuoJiDel.value=true
        goodsFilterParams.isDelete = 0

            goodsFilterParams.stockWarn = true// 下架状态
            // 这里需要后端支持库存预警查询
            // 通常是查询库存低于预警值的商品
            break
        case 'recycle': // 回收站
        isLuoJiDel.value=false
        goodsFilterParams.isDelete = 1
            // 这里需要后端支持回收站查询
            // 通常是查询已删除但未彻底删除的商品
            break
    }
    
    // 触发过滤查询
    filterTableData()
}) // 立即执行一次，确保初始加载时应用过滤



// 定义表单验证规则
const formRules = reactive<FormRules<GoodsItem>>({
    title: [{ required: true, message: "商品名称不能为空", trigger: "blur" }],
    minPrice: [{ required: true, message: "商品价格不能为空", trigger: "blur" }],
    categoryId: [{ required: true, message: "商品分类不能为空", trigger: "blur" }],
    stock: [{ required: true, message: "商品库存不能为空", trigger: "blur" }],
})

// 初始化表单数据
const initForm = reactive<GoodsAddForm>({
    title: "",
    cover: "",
    categoryId: 0,
    desc: "",
    minPrice: 0,
    minOprice: 0,
    stock: 0,
    minStock: 10,
    status: 1,
    stockDisplay: 1,
    skuType: 0,
    skuValue: "",
    ischeck: 0,
    order: 50,
    unit: "",
    expressId: 0,
    discount: 1,
    rating: 5,
    saleCount: 0,
    reviewCount: 0,
    content: ""
})

// 使用useTable钩子
const {
    pageSize,
    total,
    tableData,
    getDataByPage,
    handleSelectionChange,
    deleteIds,
    del,
    editId,
    isAddMode,
    submitHandle,
    initForm: formData,
    drawerRef,
    tableRef,
    tableHeight,
    filterTableData
} = useTable<GoodsItem, GoodsAddForm>({
    addItem: GoodsApi.add,
    deleteItem: GoodsApi.delete,
    updateItem: GoodsApi.update,
    fetchData: GoodsApi.getList,
    filterMethod: GoodsApi.filterGoods,
    formRules,
    initForm,
    title: "商品",
    filterData: goodsFilterParams
})

// 商品封面上传方式
const coverUploadType = ref('gallery') // gallery: 从图库选择, local: 本地上传

// 图片上传相关函数
const handleImageSelect = (imageList:any) => {
    if (imageList && imageList.length > 0) {
        formData.cover = imageList[0].url
    }
}


// 切换上传方式时清空图片
const handleUploadTypeChange = () => {
    formData.cover = ""
}

// 触发本地文件上传
const triggerLocalUpload = () => {
    // 如果已经上传了图片，先清除
    if(formData.cover) {
        formData.cover = ""
        return
    }
    
    const fileInput = document.createElement('input')
    fileInput.type = 'file'
    fileInput.accept = 'image/*'
    fileInput.onchange = async (e) => {
        const target = e.target as HTMLInputElement
        if (target.files && target.files.length > 0) {
            const file = target.files[0]
            // 创建表单数据
            const data = new FormData()
            data.append('file', file)
            
            try {
                // 调用上传接口
                const res = await fetch(imageApi, {
                    method: 'POST',
                    headers: {
                        [JwtTokenConstant.token]: token
                    },
                    body: data
                }).then(res => res.json())
                formData.cover = res[0].url

            } catch (error) {
                console.error('上传出错', error)
            }
        }
    }
    fileInput.click()
}

// 打开新增对话框
const openAddDrawer = () => {
    // 完全重置表单数据 - 使用类型安全的方式
    const resetForm: GoodsAddForm = {
        title: "",
        cover: "",
        categoryId: 0,
        desc: "",
        minPrice: 0,
        minOprice: 0,
        stock: 0,
        minStock: 10,
        status: 1,
        stockDisplay: 1,
        skuType: 0,
        skuValue: "",
        ischeck: 0,
        order: 50,
        unit: "",
        expressId: 0,
        discount: 1,
        rating: 5,
        saleCount: 0,
        reviewCount: 0,
        content: ""
    };
    
    // 重新赋值
    Object.assign(formData, resetForm);
    
    // 重置上传方式
    coverUploadType.value = 'gallery';
    
    isAddMode.value = true;
    drawerRef.value.open();
}

// 打开编辑对话框
const openEditDrawer = async (row: GoodsItem) => {
    try {
        // 通过ID获取最新商品数据
        const res = await GoodsApi.getById(row.id);
        if (res.code === 1 && res.data) {
            const goodsData = res.data;
            // 填充表单数据
            Object.assign(formData, {
                title: goodsData.title,
                cover: goodsData.cover,
                categoryId: goodsData.categoryId,
                desc: goodsData.desc,
                minPrice: goodsData.minPrice,
                minOprice: goodsData.minOprice,
                stock: goodsData.stock,
                minStock: goodsData.minStock,
                status: goodsData.status,
                stockDisplay: goodsData.stockDisplay,
                skuType: goodsData.skuType,
                skuValue: goodsData.skuValue,
                ischeck: goodsData.ischeck,
                order: goodsData.order,
                unit: goodsData.unit,
                expressId: goodsData.expressId,
                discount: goodsData.discount,
                rating: goodsData.rating,
                saleCount: goodsData.saleCount,
                reviewCount: goodsData.reviewCount,
                content: goodsData.content
            });
            isAddMode.value = false;
            editId.value = goodsData.id;
            drawerRef.value.open();
        } else {
            // 获取商品详情失败时的处理
            console.error("获取商品详情失败:", res.msg);
            ElMessage.error("获取商品详情失败: " + res.msg);
        }
    } catch (error) {
        console.error("获取商品详情出错:", error);
        ElMessage.error("获取商品详情出错");
    }
}

// 格式化状态
const formatStatus = (row: GoodsItem) => {
    return row.status === 1 ? '上架' : '下架'
}

// 格式化审核状态
const formatIscheck = (row: GoodsItem) => {
    if (row.ischeck === 0) return '审核中'
    if (row.ischeck === 1) return '通过'
    if (row.ischeck === 2) return '拒绝'
    return '未知'
}

// 格式化审核状态标签类型
const getIscheckTagType = (row: GoodsItem) => {
    if (row.ischeck === 0) return 'warning'
    if (row.ischeck === 1) return 'success'
    if (row.ischeck === 2) return 'danger'
    return 'info'
}

// 格式化折扣
const formatDiscount = (discount: number) => {
    return discount ? `${discount * 10}折` : '无折扣'
}

const delTable = async (id:number) => {
    if(isLuoJiDel.value) {
        messageBox('提示', `你正在删除此商品，是否继续?`).then(async () => {
            const { code } = await GoodsApi.deleteByLuoJi(id,1)
            if (code == 1) {
    filterTableData()
                
                message({
                    message: `删除商品成功`,
                    type: "success"
                })
            }
        }).catch((err) => {
            console.log(err)
            message({
                message: `取消删除商品`,
                type: "info"
            })
        })

    }else{
        del(id)
    }
}

const refute=(id:number)=>{
    messageBox('提示', `你正在恢复此商品，是否继续?`).then(async () => {
            const { code } = await GoodsApi.deleteByLuoJi(id,0)
            if (code == 1) {
    filterTableData()
                message({
                    message: `恢复商品成功`,
                    type: "success"
                })
            }
        }).catch((err) => {
            console.log(err)
            message({
                message: `取消恢复商品`,
                type: "info"
            })
        })
}

// 处理搜索表单提交
const handleFilterSearch = (formData:any) => {
    // 更新过滤参数
    if (formData.name) {
        goodsFilterParams.title = formData.name;
    } else {
        delete goodsFilterParams.title;
    }
    
    if (formData.category) {
        // 分类ID已经是数值类型，直接使用
        goodsFilterParams.categoryId = formData.category;
    } else {
        delete goodsFilterParams.categoryId;
    }
    
    if (formData.create_manager) {
        // 管理员ID已经是数值类型，直接使用
        goodsFilterParams.createManagerId = formData.create_manager;
    } else {
        delete goodsFilterParams.createManagerId;
    }
    
    // 重置页码
    goodsFilterParams.currentPage = 1;
    
    // 触发过滤查询
    filterTableData();
}

// 处理重置表单
const handleFilterReset = () => {
    // 移除表单相关的过滤条件，但保留tab过滤条件
    delete goodsFilterParams.title;
    delete goodsFilterParams.categoryId;
    delete goodsFilterParams.createManagerId;
    
    // 重置页码
    goodsFilterParams.currentPage = 1;
    
    // 触发过滤查询
    filterTableData();
}

</script>

<template>
    <div class="goodsPage">
        <div class="goods_container_left">
           <leftTab v-model="goodsTab"/>
        </div>
        <div class="goods_container_right">
            <filterFormComponent @search="handleFilterSearch" @reset="handleFilterReset"/>
           <div class="table-header">
                <div class="left">
                    <el-button type="primary" color="var(--primary-theme-color)" icon="el-icon-plus" size="small" @click="openAddDrawer">新增商品</el-button>
                    <el-button type="danger" size="small" icon="el-icon-delete" :disabled="!deleteIds.length" @click="del()">批量删除</el-button>
                </div>
            </div>
            
            <div ref="tableRef" class="table-container">
                <el-table
                    :data="tableData"
                    style="width: 100%"
                    :height="tableHeight"
                    @selection-change="handleSelectionChange"
                    
                >
                    <el-table-column type="selection" width="55" align="center" />
                    <el-table-column fixed="left" prop="id" label="ID" width="60" align="center"/>
                    <el-table-column prop="title" label="商品名称" width="180" align="center"/>
                    <el-table-column prop="cover" label="封面图" width="80" align="center">
                        <template #default="scope">
                            <el-image 
                                style="width: 40px; height: 40px" 
                                :src="scope.row.cover" 
                                :preview-src-list="[scope.row.cover]"
                                preview-teleported
                            />
                        </template>
                    </el-table-column>
                    <el-table-column label="分类" width="100" align="center">
                        <template #default="scope">
                            {{ scope.row.categoryName }}
                        </template>
                    </el-table-column>
                    <el-table-column label="价格" width="100" align="center">
                        <template #default="scope">
                            <div>¥{{ scope.row.minPrice }}</div>
                            <div v-if="scope.row.discount < 1" style="text-decoration: line-through; color: #999; font-size: 12px;">
                                ¥{{ scope.row.minOprice }}
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column label="折扣" width="80" align="center">
                        <template #default="scope">
                            <el-tag v-if="scope.row.discount < 1" type="danger">
                                {{ formatDiscount(scope.row.discount) }}
                            </el-tag>
                            <span v-else>-</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="stock" label="库存" width="70" align="center"/>
                    <el-table-column label="评分" width="100" align="center">
                        <template #default="scope">
                            <el-rate
                                v-model="scope.row.rating"
                                disabled
                                text-color="#ff9900"
                                score-template="{value}"
                            />
                        </template>
                    </el-table-column>
                    <el-table-column prop="status" label="状态" width="80" align="center">
                        <template #default="scope">
                            <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
                                {{ formatStatus(scope.row) }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="ischeck" label="审核" width="80" align="center">
                        <template #default="scope">
                            <el-tag :type="getIscheckTagType(scope.row)">
                                {{ formatIscheck(scope.row) }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="销量/评论" width="100" align="center">
                        <template #default="scope">
                            <div>{{ scope.row.saleCount }}</div>
                            <div style="color: #999; font-size: 12px;">{{ scope.row.reviewCount }}条评论</div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="createTime" label="创建时间" width="160" align="center"/>
                    <el-table-column prop="createManagerName" label="创建人" width="100" align="center"/>
                    <el-table-column prop="lastUpdateManagerName" label="修改人" width="100" align="center"/>
                    <el-table-column prop="updateTime" label="修改时间" width="160" align="center"/>
                    <el-table-column label="操作" width="150" fixed="right" align="center">
                        <template #default="scope">
                            <el-button type="success" size="small" @click="refute(scope.row.id)" v-if="goodsTab=='recycle'">恢复</el-button>
                            <el-button v-else type="primary" size="small" @click="openEditDrawer(scope.row)">编辑</el-button>
                            <el-button type="danger" size="small" @click="delTable(scope.row.id)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            
           <div class="pagination">
            <el-pagination size="small" background layout="prev, pager, next" :total="total"
            :page-size="pageSize" @current-change="getDataByPage" />
            </div> 
            
            <!-- 新增/编辑对话框 -->
            <drawer 
                ref="drawerRef" 
                :title="isAddMode ? '新增商品' : '编辑商品'" 
                direction="rtl" 
                size="50%" 
                @submit="submitHandle"
            >
                <template #rtl>
                    <el-form
                        :model="formData"
                        :rules="formRules"
                        label-width="120px"
                    >
                        <el-form-item label="商品名称" prop="title">
                            <el-input v-model="formData.title" placeholder="请输入商品名称" />
                        </el-form-item>
                        <el-form-item label="商品封面" prop="cover">
                            <div class="cover-upload-container">
                                <div class="upload-type-selector">
                                    <el-radio-group v-model="coverUploadType" @change="handleUploadTypeChange">
                                        <el-radio label="gallery">从图库选择</el-radio>
                                        <el-radio label="local">本地上传</el-radio>
                                    </el-radio-group>
                                </div>
                                <div style="display:flex;gap:10px;">
                                <div class="cover-preview" v-if="formData.cover&& coverUploadType != 'gallery'">
                                    <el-image
                                        style="width: 100px; height: 100px; border-radius: 4px;"
                                        :src="formData.cover"
                                        fit="cover"
                                        :max-scale="4" :min-scale="0.2"
                                        :preview-src-list="[formData.cover]" 
                                    />
                                </div>
                                
                                <div class="upload-component" v-if="coverUploadType === 'gallery'">
                                    <select-image 
                                        :avatar-url="formData.cover" 
                                        :multiple="false" 
                                        @select-image="handleImageSelect"
                                    />
                                </div>
                                
                                <div class="upload-component" v-else>
                                    <div class="upload" @click="triggerLocalUpload">
                                        <template v-if="formData.cover">
                                            <el-icon :size="35" color="#F56C6C">
                                                <el-icon-delete />
                                            </el-icon>
                                        </template>
                                        <template v-else>
                                            <el-icon :size="35" color="#ccc">
                                                <el-icon-plus />
                                            </el-icon>
                                        </template>
                                    </div>
                                </div>
                            </div>
                            </div>
                        </el-form-item>
                        <el-form-item label="商品分类" prop="categoryId">
                            <el-input v-model.number="formData.categoryId" placeholder="请选择商品分类" type="number" />
                        </el-form-item>
                        <el-form-item label="商品描述" prop="desc">
                            <el-input v-model="formData.desc" placeholder="请输入商品描述" type="textarea" />
                        </el-form-item>
                        <el-form-item label="原价" prop="minOprice">
                            <el-input v-model.number="formData.minOprice" placeholder="请输入商品原价" type="number" />
                        </el-form-item>
                        <el-form-item label="最低价" prop="minPrice">
                            <el-input v-model.number="formData.minPrice" placeholder="请输入商品最低价" type="number" />
                        </el-form-item>
                        <el-form-item label="折扣" prop="discount">
                            <div style="width: 95%;">
                                <el-slider
                                    v-model="formData.discount"
                                    :min="0.1"
                                    :max="1"
                                    :step="0.1"
                                    :format-tooltip="formatDiscount"
                                />
                            </div>
                            
                        </el-form-item>
                        <el-form-item label="商品库存" prop="stock">
                            <el-input v-model.number="formData.stock" placeholder="请输入商品库存" type="number" />
                        </el-form-item>
                        <el-form-item label="库存预警" prop="minStock">
                            <el-input v-model.number="formData.minStock" placeholder="请输入库存预警值" type="number" />
                        </el-form-item>
                        <el-form-item label="评分" prop="rating">
                            <el-rate v-model="formData.rating" />
                        </el-form-item>
                        <el-form-item label="销量" prop="saleCount">
                            <el-input v-model.number="formData.saleCount" placeholder="请输入销量" type="number" />
                        </el-form-item>
                        <el-form-item label="评论数" prop="reviewCount">
                            <el-input v-model.number="formData.reviewCount" placeholder="请输入评论数" type="number" />
                        </el-form-item>
                        <el-form-item label="商品状态" prop="status">
                            <el-radio-group v-model="formData.status">
                                <el-radio :label="1">上架</el-radio>
                                <el-radio :label="0">下架</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="审核状态" prop="ischeck">
                            <el-radio-group v-model="formData.ischeck">
                                <el-radio :label="0">审核中</el-radio>
                                <el-radio :label="1">通过</el-radio>
                                <el-radio :label="2">拒绝</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="库存显示" prop="stockDisplay">
                            <el-radio-group v-model="formData.stockDisplay">
                                <el-radio :label="1">显示</el-radio>
                                <el-radio :label="0">隐藏</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="商品单位" prop="unit">
                            <el-input v-model="formData.unit" placeholder="请输入商品单位" />
                        </el-form-item>
                        <el-form-item label="快递模板" prop="expressId">
                            <el-input v-model.number="formData.expressId" placeholder="请选择快递模板" type="number" />
                        </el-form-item>
                        <el-form-item label="规格类型" prop="skuType">
                            <el-radio-group v-model="formData.skuType">
                                <el-radio :label="0">单规格</el-radio>
                                <el-radio :label="1">多规格</el-radio>
                            </el-radio-group>
                        </el-form-item>
                        <el-form-item label="规格值" prop="skuValue">
                            <el-input v-model="formData.skuValue" placeholder="请输入规格值" />
                        </el-form-item>
                        <el-form-item label="排序" prop="order">
                            <el-input-number v-model="formData.order" :min="0" :max="100" />
                        </el-form-item>
                        <el-form-item label="商品详情" prop="content">
                            <el-input v-model="formData.content" type="textarea" :rows="4" placeholder="请输入商品详情" />
                        </el-form-item>
                    </el-form>
                </template>
            </drawer>
        </div>
    </div>
</template>

<style lang="scss" scoped>
.goodsPage {
    width: 100%;
    height: 100%;
    display: flex;
    gap: 6px;

    .goods_container_left {
        width: 100px;
        height: 100%;
        background-color: #FFFFFF;
        border-top-left-radius: 5px;
        border-bottom-left-radius: 5px;

        .tabs {
            height: 100%;
            width: 100%;
        }
    }

    .goods_container_right {
        width: calc(100% - 100px);
        background-color: #FFFFFF;
        border-top-right-radius: 5px;
        border-bottom-right-radius: 5px;
        display: flex;
        flex-direction: column;
        padding: 15px;
        
        .table-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin: 15px 0;
        }
        
        .table-container {
            flex: 1;
            overflow: hidden;
        }
        
        .pagination {
            margin-top: 15px;
            display:flex;
            justify-content: center;
        }
    }
}

.cover-upload-container {
    display: flex;
    flex-direction: column;
    gap: 15px;
    
    .upload-type-selector {
        margin-bottom: 5px;
    }
    
    .cover-preview {
        margin-bottom: 10px;
        border:1px solid #ccc;
        border-radius: 5px;

    }
    
    .upload {
        width: 110px;
        height: 110px;
        border: 1px dashed #ccc;
        display: flex;
        justify-content: center;
        align-items: center;
        border-radius: 5px;
        transition: 0.2s;
        cursor: pointer;

        &:hover {
            border: 1px dashed var(--primary-theme-color);
            background-color: #f5f7fa;
        }
    }
    
    .avatar-uploader {
        width: 100%;
        max-width: 360px;
    }
}

:deep(.el-pagination.is-background .el-pager li.is-active) {
    background-color: var(--primary-theme-color) !important;
    color: #FFFFFF;
}
</style>
